package com.tgy.基础学习.Thread.Synchronized;

import lombok.SneakyThrows;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/***
 * @ClassName: MySafeBank
 * @Description: 自己写的基于lock的代码
 * @Auther: 送你一块二向箔
 * @Date: 17:12 2022/4/29
 * @version : V1.0
 */
public class MySafeBank {
    public static void main(String[] args) {
        MyAccount account = new MyAccount(100,"一号钱包");
        //这里如果创建两个对象那就有两个锁，会使得锁失效
        MyDrawing myDrawing1 = new MyDrawing(account, 60, 20);
        new Thread(myDrawing1,"甲取钱50").start();
        new Thread(myDrawing1,"乙取钱50").start();
        //new Thread(new MyDrawing(account,50,20),"甲号取钱").start();
        //new Thread(new MyDrawing(account,60,20),"乙号取钱").start();
    }

}


//账户
class MyAccount {
    int money;
    String name;

    public MyAccount(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行
class MyDrawing implements Runnable{
    MyAccount account;//账户
    int drawingMoney;//取钱
    int nowMoney;//手里得钱

    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.WriteLock lock = readWriteLock.writeLock();



    //构造器
    public MyDrawing(MyAccount account, int drawingMoney, int nowMoney) {
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;
    }


    @SneakyThrows
    @Override
    /**
     * synchronized 默认锁的是this，也就是当前对象
     * 下面这种是不行的
     */
    public void run() {

        //模拟延时，放大问题发生得可能性
        lock.lock();
        if (account.money-drawingMoney<0){
            System.out.println(Thread.currentThread().getName()+"余额不足");
            return;
        }
        //Thread.sleep(1000);
        account.money -=drawingMoney;
        nowMoney += drawingMoney;
        lock.unlock();
        System.out.println(account.name+"余额为："+account.money);
        System.out.println(Thread.currentThread().getName()+"手里有："+nowMoney);

    }

}
